// index.js
// 获取应用实例
const app = getApp();
const QQMapWX = require('../../utils/qqmap-wx-jssdk.min.js');
const util = require("../../utils/util");
import Toast from "../../vant/weapp/toast/toast";
let qqmapsdk;
Page({
    data: {
        rightArr: [{
            door_list: [{
              door_name: "开门"
            }],
          }],
          addIndex: 0,
          show: false,
        headTop: "",
        headHeight: "",
        sumHeight: "",
        diy: 2,
        imgUrls: [],
        indicatorDots: false,
        autoplay: false,
        interval: 5000,
        duration: 1000,
        swiperIndex: 0, // 第一次加载默认第一张图片选中
        latitude: 0,
        longitude: 0,
        store_name: '',
        city: '', //城市名称
        indexList: [],
        is_user_show: true,
        is_user: 0,
        showUser: false,
        isOrderList: true,
        // recomLists: [],
        cardList: [{
                url: "/image/card1.png",
                name: "积分商城",
                subtitle: "快来兑换优质的礼品吧",
                link: "/pages/integral/index",
            },
            {
                url: "/image/card2.png",
                name: "会员充值",
                subtitle: "充值会员享好礼",
                link: "/pages/person/vipplas/index",
            },
        ],
        itemList: [{
                url: "/image/room.png",
                name: "开启大门",
                link: "/pages/index/room/index",
            },
            {
                url: "/image/chair.png",
                name: "包厢开门",
                link: "/pages/index/chair/index",
            },
            {
                url: "/image/meituan.png",
                name: "续费加时",
                link: "/pages/index/meituan/index",
            },
            {
                url: "/image/joinus.png",
                name: "自助验卷",
                link: "/pages/index/join/index",
            },
        ],
        recomList: [],
        pageno:0,
        // i: 0
    },
    onLoad() {
        const that = this;
        // 小程序相关参数
        app.http.post(app.api.AppInfo, {}, (res) => {
            let image = []
            for (let i = 0; i < res.data.make_image.length; i++) {
                image.push({
                    url: res.data.make_image[i],
                    type: i + 1
                })
            }
            that.setData({
                imgUrls: image,
            })
        })
        qqmapsdk = new QQMapWX({
            key: 'YN6BZ-BITW3-QGM3R-3DECZ-MAUZH-DBFDA'
        });
        that.setData({
            headTop: app.globalData.headTop,
            headHeight: app.globalData.headHeight,
            sumHeight: app.globalData.sumHeight,
        });
     
        // that.goTopOn()
        wx.getLocation()
        that.data.pageno = 0
        if (wx.getStorageSync('city')) {
            that.setData({
                city: wx.getStorageSync('city')
            })
            that.init();
        } else {
            app.http.post(
                app.api.city, {}, (res) => {
                    let key = Object.keys(res.data)[0]
                    let city = res.data[key]
                    console.log(key, city, res.data)
                    that.setData({
                        city: city.city_name,
                        latitude: city.lat,
                        longitude: city.lng,
                    })
                    that.init()
                }
            )
        }
        wx.getLocation({
            success: function (res) {
                 console.log(res)
                wx.setStorageSync('latitude', res.latitude)
                wx.setStorageSync('longitude', res.longitude)
                wx.setStorageSync("openSet", false);
                if (!wx.getStorageSync('chooseCity')) {
                    that.getLocal(res.latitude, res.longitude)
                    that.init();
                    return
                }
            },
            fail: function (fail) {
                that.init();
            },
        });
        that.getUserOrderInfo()
    },
    // 轮播跳转
    linkImg(e) {
        let type=e.currentTarget.dataset.type
        if(type===1){
            wx.navigateTo({
              url: '/pages/index/join/index',
            })
        }else if(type===2){
            wx.navigateTo({
              url: '/pages/index/hfive/index',
            })
        }
    },
    // goTopOn: function (e) {
    //     if (wx.pageScrollTo) {
    //         wx.pageScrollTo({
    //             scrollTop: 0
    //         })
    //     }
    // },
    onShow:function(){},
    Show: function () {
       
        const that = this
        // that.goTopOn()
        wx.getLocation()
     
        that.data.pageno = 0
        if (wx.getStorageSync('city')) {
            that.setData({
                city: wx.getStorageSync('city')
            })
            that.init();
        } else {
            app.http.post(
                app.api.city, {}, (res) => {
                    let key = Object.keys(res.data)[0]
                    let city = res.data[key]
                    console.log(key, city, res.data)
                    that.setData({
                        city: city.city_name,
                        latitude: city.lat,
                        longitude: city.lng,
                    })
                    that.init()
                }
            )
        }
        wx.getLocation({
            success: function (res) {
                 console.log(res)
                wx.setStorageSync('latitude', res.latitude)
                wx.setStorageSync('longitude', res.longitude)
                wx.setStorageSync("openSet", false);
                if (!wx.getStorageSync('chooseCity')) {
                    that.getLocal(res.latitude, res.longitude)
                    that.init();
                    return
                }
            },
            fail: function (fail) {
                that.init();
            },
        });
        that.getUserOrderInfo()
    },
    onReachBottom() {
        const that = this
        that.data.pageno++
        app.http.post(
            app.api.index, {
                lat: wx.getStorageSync('latitude') || 0,
                lng: wx.getStorageSync('longitude') || 0,
                title: that.data.store_name,
                city_code: that.data.city,
                pageno:that.data.pageno
            }, (res) => {
                if (res.data == "") {
                    that.setData({
                        recomList:res.data.list,
                        isOrderList: true
                    })
                } else {
                    let recomList = this.data.recomList.concat(res.data.list);
                    wx.setStorageSync('recomList', recomList)
                    this.setData({
                        recomList,
                        isOrderList: false,
                    })
               
                }
            }
        )
   
    },
    //   登录
    login(e) {
        if (wx.getStorageSync('token') == "") {
            this.setData({
                is_user_show: false,
                is_user: 1
            });
        } else if (wx.getStorageSync('mobile') == "") {
            this.setData({
                is_user_show: false,
                is_user: 2
            });
        }
    },
    // 登录遮罩层
    close(e) {
        console.log(e)
        this.setData({
            is_user_show: e.detail,
            is_user: 0
        });
    },
    // 登陆后更新
    renew(e) {
        this.setData({
            showUser: true,
        });
        wx.setStorageSync('userInfo', e.detail)
        wx.setStorageSync('mobile', e.detail.mobile)
    },
    // 首页开门
    getUserOrderInfo() {
        const that = this
        if (wx.getStorageSync('mobile') == "") {
            return
        }
        app.http.post(app.api.userOrderInfo, {}, (res) => {
          console.log(res.data)
            if (res.data.length == 0) {
                return
            }
            if (res.data[0].order === 1) {
                that.setData({
                    rightArr: res.data
                })
             
            } else {
                that.setData({
                    rightArr: {
                        door_list: [{
                            door_name: "开门"
                        }],
                    }
                })
            }
        })
    },
    search(e) {
        this.setData({
            store_name: e.detail.value
        })

        this.init()
    },
    // 打开设置
    openSet() {
        var that = this;
        if (wx.getStorageSync("openSet")) {
            wx.getSetting({
                success: (res) => {
                    var statu = res.authSetting;
                    if (!statu["scope.userLocation"]) {
                        //没授权
                        wx.showModal({
                            title: '授权',
                            content: '如果需要使用定位功能，请点击确定并在授权管理中打开“设置”，打开定位功能。',
                            complete: (res) => {
                                if (res.confirm) {
                                    wx.openSetting({
                                        success: function (res) {
                                            if (res.authSetting["scope.userLocation"]) {
                                                wx.setStorageSync("openSet", false);
                                                that.onLoad();

                                                that.init();
                                            } // 如果成功打开授权
                                            else {
                                                wx.setStorageSync("openSet", true);
                                                that.setData({
                                                    latitude: 0,
                                                    longitude: 0,
                                                });

                                                that.init();
                                            } // 如果用户依然拒绝授权
                                        },
                                        fail: function () {
                                            //调用失败，授权登录不成功
                                            return;
                                        },
                                    });
                                }

                                if (res.cancel) {
                                    that.setData({
                                        latitude: 0,
                                        longitude: 0,
                                    });
                                    that.init();
                                }
                            }
                        })

                    }
                },
            });
        }
    },
    //   门店列表
    init() {
        const that = this
        that.data.recomList=null
        app.http.post(
            app.api.index, {
                lat: wx.getStorageSync('latitude') || 0,
                lng: wx.getStorageSync('longitude') || 0,
                title: that.data.store_name,
                city_code: that.data.city,
                pageno:that.data.pageno
            }, (res) => {
                if (res.data == "") {
                    that.setData({
                        recomList:res.data.list,
                        isOrderList: true
                    })
                } else {
                    that.setData({
                        isOrderList: false,
                        recomList: res.data.list
                    })
                }
            }
        )
    },
 
    // 选择城市
    chooseCity() {
        wx.navigateTo({
            url: "/pages/index/choose/index",
        });
    },
    //功能跳转
    chooseFun(e) {
        const that = this
        const url = e.currentTarget.dataset.link;
     
        wx.navigateTo({
            url,
        });
    },
    //功能跳转
    linkTo(e) {
        console.log(e);
        const url = e.currentTarget.dataset.link;
        wx.navigateTo({
            url,
        });
    },
    // 方法
    swiperChange(e) {
        // console.log(e);
        const that = this;
        that.setData({
            swiperIndex: e.detail.current,
        });
    },
    // 包房预定
    // toRoom(e) {

    //     wx.navigateTo({
    //         url: "/pages/index/room/index?room_id=" + e.currentTarget.dataset.roomid,
    //     });

    // },
    getLocal(latitude, longitude) {
        let that = this;
        qqmapsdk.reverseGeocoder({
            location: {
                latitude: Number(latitude),
                longitude: Number(longitude)
            },
            success: function (res) {
                let city = res.result.ad_info.city
                if (city == wx.getStorageSync('city')) {
                    return
                }
                that.setData({
                    city,
                    latitude,
                    longitude
                })
                wx.setStorageSync('city', city)
                that.init();
            },

            fail: function (res) {
                console.log(res);
            },
            complete: function (res) {
                // console.log(res);
            }
        });
    },
    onShareAppMessage() {

    },
    onShareTimeline() {},
    onPullDownRefresh:function(){
        this.onRefresh();
      },
    onRefresh:function(){
        //导航条加载动画
        wx.showNavigationBarLoading()
        //loading 提示框
        wx.showLoading({
          title: 'Loading...',
        })
        console.log("下拉刷新啦");
        this.Show();
        setTimeout(function () {
          wx.hideLoading();
          wx.hideNavigationBarLoading();
      
    
          //停止下拉刷新
          wx.stopPullDownRefresh();
        }, 2000)
      },
// 开门
      opendoor(e) {
        let that = this;
        // order:订单数量，0为没有，显示暂无预约，1为一个，直接开门，2及2以上跳转页面，自行选择开门订单
        // order_type：1为玩法订单，2为包厢订单，优先玩法
        let i = that.data.rightArr.length
        if (wx.getStorageSync('token') === "") {
          Toast.fail("请先登录")
          return
        }
        if (wx.getStorageSync('mobile') === "") {
          Toast.fail("请先绑定手机号")
          return
        }
    console.log(that.data.rightArr)
 
   
        if (that.data.rightArr.length === 0 ) {
     
          Toast.fail("暂无预约订单")
          return
        }
        // 只有一个订单
        if (i === 1) {
          // 订单是玩法
          if (that.data.rightArr[0].order_type === 1) {
            that.open1(i)
            // 订单是包厢
          } else if (that.data.rightArr[0].order_type === 2) {
            that.open2(i)
          }
        } else {
          wx.reLaunch({
            url: '/pages/order/index',
          })
        }
  
  
      },
//续时
      extend() {
        const that = this
        if (wx.getStorageSync('token') == "") {
          that.triggerEvent("is_user_show", false);
          return
        }
        if (wx.getStorageSync('mobile') == "") {
          that.triggerEvent("is_user_show", false);
          return
        }
        if (that.data.rightArr == "") {
          Toast.fail("暂无预约订单")
          return
        }
        if (that.data.rightArr[0].order === 1) {
          if (that.data.rightArr[0].order_type !== 2) {
            Toast.fail("该订单不可延长")
          } else if (that.data.rightArr[0].order_type === 2) {
            that.getRenewal()
            that.setData({
              show: true,
            });
          }
        } else {
          wx.reLaunch({
            url: '/pages/order/index',
          })
        }
      },
       // 开玩法门
       open1(i) {
        const that = this
        wx.getLocation({
          type: "wgs84",
          success: function (res) {
            app.http.post(app.api.DoorSeat, {
              order_on: that.data.rightArr.order_on,
              door_id: that.data.rightArr.door_list[i].door_id,
              lat: res.latitude,
              lng: res.longitude
            }, res => {
              if (res.code === 200) {
                Toast.success("开门成功")
              } else {
                Toast.fail(res.message)
              }
  
            })
          },
          fail(e) {
            wx.setStorageSync("openSet", true);
            that.openSet();
          },
        });
  
      },
      // 包厢法门
      open2(i) {
        console.log(i)
        const that = this
        wx.getLocation({
          type: "wgs84",
          success: function (res) {
            app.http.post(app.api.DoorIndex, {
              order_on: that.data.rightArr[0].order_on,
              door_id: that.data.rightArr[0].door_list[0].door_id,
              lat: res.latitude,
              lng: res.longitude
            }, res => {
              if (res.code === 200) {
                Toast.success("开门成功")
              } else {
           
                Toast.fail(res.message)
              }
  
            })
          },
          fail(e) {
            wx.setStorageSync("openSet", true);
            that.openSet();
          },
        });
  
      },

      getRenewal() {
        app.http.post(app.api.orderRenewal, {
          order_on: this.data.rightArr[0].order_on
        }, (res) => {
          this.setData({
            add: res.data
          })
          this.getTime()
        })
      },
      getTime() {
        const that = this
        let start = that.data.add.order.end_time * 1000
        let timestart = util.formatHS(start)
        console.log(that.data.addIndex)
        // let timeEnd=
        let next_time = new Date(timestart.replace(/\-/g, "/")).setHours(
          new Date(timestart.replace(/\-/g, "/")).getHours() + that.data.add.renewal[that.data.addIndex].time
        );
 
        let timeEnd = util.formatH(next_time);
      
        that.setData({
          timestart,
          timeEnd
        })
      },
      addTime() {
        const that = this;
        app.http.post(app.api.renewalOrder, {
          order_on: that.data.rightArr[0].order_on,
          happy_id: that.data.add.renewal[that.data.addIndex].happy_id
        }, (res) => {
          console.log(res.data.order_on)
          wx.navigateTo({
            url: '/pages/index/order/index?order_on=' + res.data.order_on + "&from=renew",
          })
          that.setData({
            show: false
          })
        })
      },
      onClose(e) {
        this.setData({
          show: false,
        });
      },
});